<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closePopup" :show="showSpecsPopup" round
            custom-style="width: 100%;background:#ffffff;overflow: hidden; height:70%">
            <view class="popup-content">

                <view class="popup-main">
                    <view style="display: flex; justify-content: space-between;">
                        <!-- 商品内容 -->
                        <view class="goodsDetail">
                            <view class="goodsPic"> <img
                                    src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png"
                                    alt="" mode="widthFix"> </view>
                            <view class="goodsText">
                                <view class="goods_price">
                                    <view class="goods_price_num r13">¥{{ price }}</view>
                                    <view class="goods_price_text r8">最多可用</view>
                                    <view class="goods_price_num"> <img
                                            src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                            alt="" style="height: 14px; width: 14px; margin-right: 7px;" /> {{ score }}
                                    </view>
                                </view>
                                <view class="goods_T">{{ ebStoreProduct.storeName }} {{ selectedSuk }}</view>
                            </view>
                        </view>
                        <!-- 关闭弹窗按钮 -->
                        <view>
                            <van-icon name="cross" color="#FFFFFF" size="15" @click="closePopup" />
                        </view>
                    </view>
                    <scroll-view class="scroll-content " scroll-y :lower-threshold="120" show-scrollbar="false">

                        <!-- 规格   口味 -->

                        <view class="specs-box taste" v-for="(item, index) in ebProductAttr" :key="index" :id="item.id">
                            <view class="specs-box-title">{{ item.attrName }}</view>
                            <view class="specs-box-select">
                                <view class="popup-sort">
                                    <view
                                        class="popup-item inStock"
                                        :class="{ cur_border: (isSelected(item.id,single) ) , dis_border: single.disabled , 'dis_border':(single.disabled || single.outOfStock)}"
                                         v-for="(single, ind) in item.ebProductAttrSecond" :key="ind"
                                        :id="single.id"
                                        @click="selectSpec(item.id,item.attrName,single)">
                                        {{ single.attrName }}
                                        <span v-if="single.outOfStock" class="out-of-stock-tag">缺货</span>
                                    </view>
                                </view>
                            </view>
                        </view>
                        <!-- 数量 -->
                        <view class="specs-box number">
                            <view class="specs-box-title">数量 <span
                                    v-if="ebStoreProduct.quotaNum && ebStoreProduct.quotaNum > 0">（限购{{ ebStoreProduct.quotaNum }}{{ ebStoreProduct.unitName }}）</span>
                            </view>
                            <view class="specs-box-select">
                                <van-stepper :value="stepperValue" min="1" :max="ebStoreProduct.quotaNum" integer />
                            </view>
                        </view>

                        <van-toast id="van-toast" />
                    </scroll-view>

                </view>
                <!-- <view class="goodsAction nav_box" v-if="parentSign==='detail'">
                    <van-goods-action class="my-goods-action" v-if="buttonStatus === 0">
                        <van-goods-action-button
                            class="my-action-buttonL"
                            plain
                            color="#111111"
                            text="加入购物车"
                            @click="addToCart" />
                        <van-goods-action-button color="#FF6203" text="立即购买" @click="onClickBuy" />
                    </van-goods-action>
                    <van-goods-action v-else>
                        <van-goods-action-button v-if="buttonStatus === 1" color="#FF6203" text="加入购物车" @click="addToCart" />
                        <van-goods-action-button v-if="buttonStatus===2 && biaozhi!=='find'" color="#FF6203" text="立即购买" @click="onClickBuy" />
                        <van-goods-action-button v-if="buttonStatus===2 && biaozhi==='find'" color="#FF6203" text="立即拼团" @click="onClickGroupBuy" />
                    </van-goods-action>
                </view> -->
                <view class="goodsAction nav_box" v-if="parentSign === 'cart'">
                    <van-goods-action class="my-goods-action" id="my-goods-action">
                        <van-goods-action-button color="#FF6203" text="确定" @click="onClickBuy" />
                    </van-goods-action>
                </view>
            </view>
        </van-popup>
    </view>
</template>
<script>
import Toast from '@/wxcomponents/vant/toast/toast'

import { addToShoppingCartApi } from '@/api/shoppingCart'

export default {
    props: {
        showSpecsPopup: {
            type: Boolean,
            default: () => false
        },
        roleName: {
            type: String,
            default: () => ''
        },
        buttonStatus: {
            type: Number,
            default: () => 0
        },
        parentSign: {
            type: String,
            default: () => ''
        },
        biaozhi: {
            type: String,
            default: () => ''
        },
      
        ebStoreProduct: {
            type: Object,
            default: () => { }
        },
        //   ebProductAttr: {
        //     type: Array,
        //     default: () => []
        // },
        // ebStoreProductAttrValue: {
        //     type: Array,
        //     default: () => []
        // },
        // ebStoreProductAttrRelationDTO: {
        //     type: Array,
        //     default: () => []
        // },

    },
    data() {
        return {
            curSpecsOuterIndex: -1,
            curSpecsInnerIndex: -1,
            curWeight: -1,

            date: '',
            show: true,
            title: 'Hello',
            option: {},
            url: '',
            stepperValue: 1,
            
            price: '160',
            score: '160',
            curObj: [],
            specsArray: [],
            newSpecsList: [],
            productId: undefined,
            productAttrValueId: undefined,
            chooseSize: '',
            chooseColor: '',

            selectedSpecs: {},// 存放规格名称
            selectedSpecsIds:{},  // 存放规格id
            // 初始化时将所有规格选项设为可用
            initialized: false,
            selectedSpecPids:[],
            selectedSukIds:[],
            selectedSuk:'',
            stockInitialized: false,
            ebProductAttr: [
                { 
                    id: 121,
                    pid: 0,
                    attrName: '颜色',
                    ebProductAttrSecond: [
                        {
                            "id": 125,
                            "pid": 121,
                            "attrName": "格物致知蓝咖"
                        },
                        {
                            "id": 124,
                            "pid": 121,
                            "attrName": "格物致知红色"
                        }
                    ]
                },
                {
                    id : 126,
                    pid: 0,
                    "attrName": "尺码",
                    "ebProductAttrSecond":[
                        {
                            "id":127,
                            "pid":126,
                            "attrName":"200 * 27cm"
                        },
                        {
                            "id":128,
                            "pid":126,
                            "attrName":"240 * 30cm"
                        }
                    ]
                }
            ],
            ebStoreProductAttrValue: [
                {
                    "id": 21,
                    "productId": 3,
                    "suk": "格物致知红色,200 * 27cm",
                    "stock": 10,
                    "sales": 0,
                    "price": 374.00,
                    "integral": 0.00,
                    "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
                    "unique": null,
                    "cost": 100.00,
                    "barCode": "",
                    "otPrice": 412.00,
                    "weight": 0.50,
                    "volume": 0.00,
                    "brokerage": 0.00,
                    "brokerageTwo": 0.00,
                    "type": 0,
                    "quota": 0,
                    "quotaShow": 0,
                    "isDel": false,
                    "attrValue": null
                }, {
                    "id": 22,
                    "productId": 3,
                    "suk": "格物致知红色,240 * 30cm",
                    "stock": 677,
                    "sales": 1,
                    "price": 374.00,
                    "integral": 0.00,
                    "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
                    "unique": null,
                    "cost": 100.00,
                    "barCode": "",
                    "otPrice": 412.00,
                    "weight": 0.50,
                    "volume": 0.00,
                    "brokerage": 0.00,
                    "brokerageTwo": 0.00,
                    "type": 0,
                    "quota": 0,
                    "quotaShow": 0,
                    "isDel": false,
                    "attrValue": null
                }, {
                    "id": 19,
                    "productId": 3,
                    "suk": "格物致知蓝咖,200 * 27cm",
                    "stock": 0,
                    "sales": 0,
                    "price": 374.00,
                    "integral": 30.00,
                    "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
                    "unique": null,
                    "cost": 100.00,
                    "barCode": "",
                    "otPrice": 412.00,
                    "weight": 0.50,
                    "volume": 0.00,
                    "brokerage": 0.00,
                    "brokerageTwo": 0.00,
                    "type": 0,
                    "quota": 0,
                    "quotaShow": 0,
                    "isDel": false,
                    "attrValue": null
                }, {
                    "id": 20,
                    "productId": 3,
                    "suk": "格物致知蓝咖,240 * 30cm",
                    "stock": 366,
                    "sales": 0,
                    "price": 374.00,
                    "integral": 10.00,
                    "image": "crmebimage/public/maintain/2021/12/25/5486775d8cad4fd8adfc254d2e93857cn0wu5hq8f4.jpg",
                    "unique": null,
                    "cost": 100.00,
                    "barCode": "",
                    "otPrice": 412.00,
                    "weight": 0.50,
                    "volume": 0.00,
                    "brokerage": 0.00,
                    "brokerageTwo": 0.00,
                    "type": 0,
                    "quota": 0,
                    "quotaShow": 0,
                    "isDel": false,
                    "attrValue": null
                }
            ],

            ebStoreProductAttrRelationDTO: [
                {
                    "productId": 3,
                    "valueId": 19,
                    "specId": 125,
                    "specName": "格物致知蓝咖",
                    "specParentId": 121,
                    "specParentName": "颜色"
                },
                {
                    "productId": 3,
                    "valueId": 19,
                    "specId": 127,
                    "specName": "200*27cm",
                    "specParentId": 126,
                    "specParentName": "尺码"
                },
                {
                    "productId": 3,
                    "valueId": 20,
                    "specId": 125,
                    "specName": "格物致知蓝咖",
                    "specParentId": 121,
                    "specParentName": "颜色"
                },
                {
                    "productId": 3,
                    "valueId": 20,
                    "specId": 128,
                    "specName": "240*30cm",
                    "specParentId": 126,
                    "specParentName": "尺码"
                },
                {
                    "productId": 3,
                    "valueId": 21,
                    "specId": 124,
                    "specName": "格物致知红色",
                    "specParentId": 121,
                    "specParentName": "颜色"
                },
                {
                    "productId": 3,
                    "valueId": 21,
                    "specId": 127,
                    "specName": "200*27cm",
                    "specParentId": 126,
                    "specParentName": "尺码"
                },
                {
                    "productId": 3,
                    "valueId": 22,
                    "specId": 124,
                    "specName": "格物致知红色",
                    "specParentId": 121,
                    "specParentName": "颜色"
                },
                {
                    "productId": 3,
                    "valueId": 22,
                    "specId": 128,
                    "specName": "240*30cm",
                    "specParentId": 126,
                    "specParentName": "尺码"
                }
            ],
        }
    },
    watch: {

    },
    computed: {
        // sortedArr() {
        //     return this.curObj.slice().sort((a, b) => a.specCategoryIndex - b.specCategoryIndex);
        // }
    },
    onload(data) {
        this.price = this.ebStoreProduct.price
        this.score = this.ebStoreProduct.integral
        this.productId = this.ebStoreProduct.id
    },
    onReady() {
        // 创建一个空对象用于存储整合后的数据
        const integratedData = {};

        // 遍历ebStoreProductAttrValue数组，以id为键存储对象
        this.ebStoreProductAttrValue.forEach(item => {
            integratedData[item.id] = { ...item, relations: [] };
        });

        // 遍历ebStoreProductAttrRelationDTO数组，合并关系数据
        this.ebStoreProductAttrRelationDTO.forEach(relation => {
            const valueId = relation.valueId;
            if (integratedData[valueId]) {
                integratedData[valueId].relations.push(relation);
            }
        });

        // 将整合后的对象转换为数组
        const resultArray = Object.values(integratedData);
        console.log(integratedData,'integratedData',resultArray,'resultArray');
        // 初始化库存状态
        this.initStockStatus();
    },
    methods: {
        // 页面一开始进行判断   如果含有由某一规格的stock都为0   则这个规格库存为0   显示缺货
        initStockStatus() {
            if (this.stockInitialized) return;
            // debugger
            this.ebProductAttr.forEach(specGroup => {
                specGroup.ebProductAttrSecond.forEach(spec => {
                    spec.outOfStock = false;
                    spec.disabled = false;
                    // const allStockZero = this.ebStoreProductAttrValue.every(item => {
                    //     console.log(item.suk.includes(spec.attrName),'item.suk')
                    //     if (item.suk.includes(spec.attrName)&&item.stock === 0) {
                    //         return item.stock === 0;
                    //     }
                    //     return true;
                    // });
                    const filteredItems = this.ebStoreProductAttrValue.filter(item => item.suk.includes(spec.attrName));
                    const allStockZero = filteredItems.every(item => item.stock === 0);
                    if(allStockZero){
                        spec.outOfStock = true;
                        spec.disabled = true
                    }
                    console.log(allStockZero,'allStockZero')
                });
            });
            console.log(this.ebProductAttr,'ebProductAttr')

            this.stockInitialized = true;
        },


        init() {
            if (!this.initialized) {
                this.ebProductAttr.forEach(single => {
                    single.ebProductAttrSecond.forEach(every => {
                        every.disabled = false;
                        every.outOfStock=false
                    });
                });
                this.initialized = true;
            }
        },
        selectSpec(pid, parentSpecs, spec) {
            console.log(pid, parentSpecs,'parentSpecs', spec,'parentSpecs');
            this.selectedSpecs[pid] = spec.attrName;
            this.selectedSpecsIds[spec.id] = spec.attrName;
            console.log(this.selectedSpecs, this.selectedSpecsIds,'selectedSpecs');
            this.updateStockStatus();
            this.selectedSuk = Object.values(this.selectedSpecs).join(',');
            const matchingAttrValue = this.ebStoreProductAttrValue.find(item => item.suk === this.selectedSuk);
            console.log(matchingAttrValue,'matchingAttrValue');
            if (matchingAttrValue) {
                this.price = matchingAttrValue.price;
                this.score = matchingAttrValue.integral;
            }
        },
        updateStockStatus() {
            // 假设当前选择的是颜色规格，更新尺码规格的状态
            if (this.selectedSpecs[121]) { // 假设 121 是颜色规格的 pid
                const selectedColor = this.selectedSpecs[121];
                this.ebProductAttr.forEach(group => {
                    if (group.id === 126) { // 假设 126 是尺码规格的 pid
                        group.ebProductAttrSecond.forEach(sizeSpec => {
                            sizeSpec.disabled = false;
                            sizeSpec.outOfStock = false;
                            const combinedSuk = `${selectedColor},${sizeSpec.attrName}`;
                            const matchingAttrValue = this.ebStoreProductAttrValue.find(item => item.suk === combinedSuk);
                            if (matchingAttrValue && matchingAttrValue.stock === 0) {
                                sizeSpec.disabled = true;
                                sizeSpec.outOfStock = true;
                            }
                        });
                    }
                });
            }
        },
        updateStockStatus() {
            // 重新计算库存状态
            this.ebProductAttr.forEach(group => {
                group.ebProductAttrSecond.forEach(spec => {
                    spec.disabled = false;
                    spec.outOfStock = false;
                    const newSelectedSpecs = {...this.selectedSpecs };
                    newSelectedSpecs[group.id] = spec.attrName;
                    const newSuk = Object.values(newSelectedSpecs).join(',');
                    const matchingAttrValue = this.ebStoreProductAttrValue.find(item => item.suk === newSuk);
                    if (matchingAttrValue && matchingAttrValue.stock === 0) {
                        spec.outOfStock = true;
                        spec.disabled = true;
                    }
                });
            });
        },
        isSpecSelected(specIds) {
            return specIds.every(spec => {
                const parts = spec.split(' ')[0].split('*');
                console.log(parts,'parts---')
                const id = parts.length === 2? parts[0].trim() : spec;
                console.log(id,'id')
                return this.selectedSuk.includes(id);
            });
        },
        isSelected(pid,single) {
            return this.selectedSpecs[pid] === single.attrName;
        },
        isOutOfStock() {
            const selectedSuk = Object.values(this.selectedSpecs).join(',');
            return this.ebStoreProductAttrValue.some(item => item.suk === selectedSuk && item.stock === 0);
        },

        // // 选重量
        // onClickWeight (val, e, item) {
        //     this.curWeight = val
        // },
        // 关闭弹窗
        closePopup() {
            this.$emit('closeSpecsPopup')
        },

        // 加入购物车
        addToCart() {
            // this.$emit('addToCart')
            if (this.curObj.length === 0) {
                Toast('请选择规格')
            } else {
                if (this.curObj.length === this.specsList.length) {
                    const params = {
                        cartId: 0,
                        cartNum: 0,
                        cartType: "",
                        combinationId: 0,
                        productAttrValueId: this.productAttrValueId,
                        productId: this.productId,
                        selected: false
                    }
                    addToShoppingCartApi(params).then((res) => {
                        if (res.code === 200) {
                            Toast('加入购物车成功')
                            this.$emit('closeSpecsPopup')
                        }
                    })

                } else if (this.curObj.length < this.specsList.length) {
                    const idObject = {};
                    this.curObj.forEach((obj) => {
                        idObject[obj.pid] = true;
                    });
                    console.log(idObject, 'idObject')
                    const missingItems = this.specsList.filter((obj) => !idObject[obj.id]).map((obj) => obj.attrName);
                    console.log(missingItems, 'missingItems')

                    Toast('请选择' + missingItems)
                } else {

                }
            }
        },

        // 立即购买
        onClickBuy() {
            // this.$emit('onClickCart')
            if (this.curObj.length === 0) {
                Toast('请选择规格')
            } else {
                if (this.curObj.length === this.specsList.length) {
                    Toast('加入购物车成功')
                    // Toast('res.msg')
                    this.$emit('closeSpecsPopup')
                } else if (this.curObj.length < this.specsList.length) {
                    const idObject = {};
                    this.curObj.forEach((obj) => {
                        idObject[obj.pid] = true;
                    });
                    console.log(idObject, 'idObject')
                    const missingItems = this.specsList.filter((obj) => !idObject[obj.id])
                        .map((obj) => obj.attrName);
                    console.log(missingItems, 'missingItems')

                    Toast('请选择' + missingItems)
                } else {

                }
            }
        },
        onClickGroupBuy() {
            const params = {}
            uni.navigateTo({
                url:
                    '/pages/shoppingCart/settlement?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },
        // 加入购物车
        addToShoppingCartMethod() {

            return new Promise((resolve, reject) => {
                addToShoppingCartApi().then((res) => {
                    console.log(res, 'res')
                    if (res.code === 200) {

                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        }
    }
}
</script>
<style lang="scss" scoped>
// @import '@/styles/variables.scss';

// 最外层
.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow-y: auto;
    z-index: -2;
    scrollbar-width: none;
    /* 针对Firefox */
}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}

// 提示框
.popup-content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 24px;
    border-radius: 16px;
    overflow: hidden;
    // height:100vh;
    height: 100%;

    .popup-main {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        height: calc(100% - 30px);
    }

    .goodsDetail {
        display: flex;
        // align-items: center;
        padding-bottom: 8px;
        width: 100%;
    }

    .goodsPic {
        width: 25%;
        // 让图片居中
        display: flex;
        justify-content: center;
        align-items: center;

        img {
            width: 100%;
            height: auto;
            // width: 89px;
            // height: 89px;
        }
    }

    .goodsText {
        padding-left: 17px;
        position: relative;
        width: 75%;
        display: flex;
        flex-direction: column;
        justify-content: center;

        // 价格
        .goods_price {
            position: absolute;
            top: 5%;
            display: flex;
            align-items: center;
            // margin-top: 18px;
            text-align: left;
            // line-height: 20px;

            .goods_price_num {
                font-weight: bolder;
                font-size: 20px;
                text-align: left;
                color: #111111;
                line-height: 20px;
            }

            .goods_price_text {
                // font-weight: bold;
                font-size: 12px;
                text-align: left;
                color: #111111;
                line-height: 12px;
            }
        }

        .goods_T {
            position: absolute;
            // bottom: 10%;
            top: 45%;
            font-size: 12px;
            text-align: left;
            color: #888888;
            // line-height: 12px;
            // margin-top: 18px;
        }

    }

    // 选规格   口味 重量 数量
    .specs-box {
        margin-top: 28px;

        .specs-box-title {
            // font-weight: 400;
            font-size: 14px;
            text-align: left;
            color: #666666;
            line-height: 14px;

            span {
                // font-weight: 400;
                font-size: 14px;
                text-align: left;
                color: #111111;
                line-height: 14px;
            }
        }

        .specs-box-select {
            margin-top: 15px;
        }

        .popup-sort {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: wrap;
        }

        .popup-item {
            margin-right: 12px;
            margin-bottom: 12px;
            height: 28px;
            line-height: 28px;
            padding-left: 24px;
            padding-right: 24px;
        }

        // 有库存
        .inStock {
            border: 1px solid #D6D6D6;
            font-size: 13px;
            text-align: center;
            color: #333333;

            &.active {
                border: 1px solid #111111;
                color: #111111;
                font-size: 14px;
            }
        }

        // 某一规格没有了
        .soldOut {
            font-size: 13px;
            color: #999999;
            border: 1px solid #999999;
        }
    }
}

.number {
    padding-bottom: 20px;
}

.l20 {
    margin-left: 20px;
}

.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}

.my-goods-action {
    .van-goods-action-button {
        color: green;
        background-color: orange;
    }
}

::v-deep #my-goods-action .van-goods-action, .van-goods-action--safe{
    border-top: 1px solid #f9f9f9 !important;
}

::v-deep .minus-class,
.van-stepper__minus,
.van-stepper__minus--disabled {
    border-radius: 50px !important;
}

// stepper    步进器
// 左边的数字
::v-deep .minus-class,
.van-stepper__minus {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #111111 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 及不能被点击的最小数字
::v-deep .van-stepper__minus--disabled {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #999999 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 中间的数字
::v-deep .input-class,
.van-stepper__input {
    border-radius: 50px !important;
    background-color: transparent !important;
}

// 右侧最大的数字
::v-deep .plus-class,
.van-stepper__plus {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #111111 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 以及不能被点击状态
::v-deep .van-stepper__plus--disabled {
    border-radius: 50px !important;
    border: 1px solid #999999 !important;
    background-color: #ffffff !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}


.normal {
    display: inline-block;
    width: 140px;
    height: 40px;
    line-height: 40px;
    margin: 10px;
    border: 1px solid #ccc;
    text-align: center;
}

.cur_border {
    border-color: #111111 !important;
    color: #111111;
    /* color: #000; */
}

.dis_border {
    position: relative;
    border-color: #999999 !important;
    font-size: 13px;
    color: #999999 !important;
    pointer-events: none;
}


.dis_border::before {
    content: "缺货";
    position: absolute;
    width: 40px;
    height: 20px;
    background: #fff;
    top: -20px;
    right: -10px;
    font-size: 10px;
}

.out-of-stock-tip {
    color: red;
    margin-top: 20px;
}
.out-of-stock-tag {
    color: red;
    margin-left: 5px;
}


</style>
